<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/5/31
 * Time: 18:00
 */

namespace app\admin\controller;

use app\common\enum\IndexEnum;
use app\common\enum\StatusEnum;
use app\common\enum\TypeEnum;
use app\common\service\JurisdictionService;
use app\common\validate\AdminValidate;
use app\common\validate\IDMustBePostiveInt;
use app\common\validate\UserValidate;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\Role as RoleModel;
use app\common\model\Auth as AuthModel;
use app\common\model\UserRoleRelation as UserRoleRelationModel;
use think\Exception;
use think\facade\Request;
use app\common\model\SysInternationAreaConfig as SysInternationAreaConfigModel;
use app\common\model\Admin as AdminModel;

class Admin extends Common
{
    /**
     * 管理员列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index() {
        if (Request::isAjax()) {
            $where = [];
            $data = AdminModel::getAdminList($where);
            $data = $data->toArray();
            foreach ($data['data'] as &$v) {
                $v['role_names'] = RoleModel::getNames($v['role_ids']);
            }

            return return_data('管理员列表', 0, $data['data'], $data['total']);
        }
        return view();
    }

    /**
     * 添加或者编辑管理员
     * @return \think\response\Json|\think\response\View
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function save_admin() {
        $id = input('param.id', 0);
        if (request()->isAjax()) {

            $user_validate = new AdminValidate();
            $user_validate->goCheck();
            $param = $user_validate->getDataByRule(input('param.'));
            $data = AdminModel::createOrUpdateAdmin($param, $id);
            return $data;
        } else {
            $data = [];
            if ($id > 0) {
                $data = AdminModel::get($id);
            }

            $this->assign('data', $data);

            return view();
        }
    }

    /**
     * 修改管理员状态
     * @return \think\response\Json
     * @throws Exception
     */
    public function save_status() {
        (new IDMustBePostiveInt())->goCheck();
        try {
            $id = input('param.id');
            $admin = AdminModel::get($id);
            if (!$admin) {
                throw new Exception('管理员不存在');
            }
            $status = input('param.status', 0);
            if (!in_array($status, [StatusEnum::ADMIN_VALID, StatusEnum::ADMIN_DISABLED])) {
                throw new Exception('参数错误');
            }
            $admin->save(['status' => $status]);
            return return_data('修改成功');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 获取角色json数据
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function get_tag_data() {
        $where = [];
        $where['status'] = StatusEnum::ROLE_VALID;
        $data = RoleModel::all($where);

        $id = input('param.id', 0);
        $selected = '';
        if ($id > 0) {
            $selected = (new AdminModel)->where('id', '=', $id)->value('role_ids');
        }

        return json(['code' => 0, 'data' => $data, 'selected' => explode(',', $selected)]);
    }

    /**
     * 查看管理员权限
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show_auth() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        if(Request::isAjax()) {
            $role_ids = session('szb_admin.role_ids');

            // 获取角色数据
            $auth_ids = RoleModel::getAdminAuthIds($role_ids);

            $auths = (AuthModel::where(function ($query) use($auth_ids) {
                $query->where('id', 'in', $auth_ids);
            })->order('order desc, id desc')->select())->toArray(); // 获取所有权限
            foreach ($auths as &$v) {
                $v['checked'] = 1;
            }
            $auths = JurisdictionService::list_to_tree($auths, 'id', 'parent_id'); // 将分类列表数据转换为无限极树状结构
            // 获取节点配置信息
            return json(['code' => 0, 'tree' => $auths]);
        } else{
            $this->assign('id', $id);
            return view();
        }
    }
}